<!--  -->
<template>
  <div class="">
    <div class="header el-icon-arrow-left" @click="$router.go(-1)">
      <span> 修改帖子 </span>
    </div>
    <hr />
    <div class="header-content">
      <div class="select">
        <div class="selectTitle">
          <el-select v-model="form.parentTypeId">
            <el-option
              v-for="item in commentType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
        <div class="selectTitle">
          <el-select v-model="form.typeId">
            <el-option
              v-for="item in commentTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="header-button">
        <el-switch
          style="margin-right: 5px"
          v-model="form.isPrivate"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="所有用户可见"
          inactive-text="仅社团可见"
          :active-value="false"
          :inactive-value="true"
          v-show="this.$store.state.isJoin"
        >
        </el-switch>
        <el-button type="primary" round @click="mod">修改</el-button>
        <el-button type="info" round @click="reset">重置</el-button>
      </div>
    </div>
    <!-- 富文本编辑器 -->
    <div style="width: 80%; margin: 0 auto">
      <quillEditor
        v-model="content"
        ref="editorRef"
        :options="editorOption"
        @focus="onEditorFocus($event)"
        @blur="onEditorBlur($event)"
        @change="onEditorChange($event)"
        class="editor"
        v-if="editorReady"
      />
    </div>
<el-upload
  class="avatar-uploader"
  action="http://106.52.100.34:8222/minioservice/minio-upload/upload"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :data="uploadData"
  :headers="headers"
  :before-upload="beforeAvatarUpload">
  <img v-if="form.postImage" :src="form.postImage" class="avatar">
  <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件，且不超过2mb
      </div>
</el-upload>
  </div>
</template>

  <script>
import { getParentCommentType, getAllCommentType } from "@/api/comment/index";
import { addPost, getIdPost, modPosts } from "@/api/comment/postManagement";
import Cookies from "js-cookie";

export default {
  name: "pushComment",
  asyncData({ query }) {
    return {
      postId: query.id,
    };
  },
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      postDetails: {}, //帖子详细
      form: {
        parentTypeId: "",
        typeId: "",
        postImage: "",
        content: "",
        isPrivate: false,
      },
      fileList: [],
      headers: {},
      uploadData: { bucketName: "comment" },
      commentType: [],
      commentTypeList: [],
      content: "",
      postImage: "",
      editorReady: false, // 控制 Quill 编辑器的加载状态
      editorOption: {
        theme: "snow",
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
            ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
            [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
            [{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
            [{ indent: "-1" }, { indent: "+1" }],
            //[{ size: sizes }], // 配置字号
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
            //[{ font: fonts }], //显示字体选择
            [{ align: [] }], // 对齐方式-----[{ align: [] }]
            ["clean"], // 清除文本格式-----['clean']
            //["link", "image", "video"], // 链接、图片、视频-----
          ],
        },
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    // 观察 parentTypeId 的变化
    "form.parentTypeId"() {
      // 当 parentTypeId 发生变化时，调用 getAllCommentTypes 方法
      this.getAllCommentTypes();
    },
  },
  //方法集合
  methods: {
    //返回帖子详细页面
    back() {
      this.$router.push("/userInfoForm");
    },

    onSubmit() {
      console.log("submit!");
    },
    // 失去焦点事件
    onEditorBlur(quill) {
      console.log("editor blur!", quill);
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      console.log("editor focus!", quill);
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      console.log("editor ready!", quill);
    },
    // 内容改变事件
    onEditorChange({ quill, html, text }) {
      console.log("editor change!", quill, html, text);
      this.form.content = html;
    },
    //重置按钮，重置富文本输入框
    reset() {
      this.content = "";
    },

    //上传图片
    handleAvatarSuccess(response) {
      // 假设上传成功后，服务器返回图片的URL
      if (response.success) {
        console.log(response);
        this.form.postImage = response.data.url;
      } else {
        this.$message.error("上传失败");
      }
    },
    beforeAvatarUpload(file) {
      // 可以在这里添加文件类型和大小的校验
      if (file.type !== "image/jpeg" && file.type !== "image/png") {
        this.$message.error("头像必须是jpg或png格式!");
        return false;
      } else if (file.size / 1024 / 1024 > 2) {
        this.$message.error("头像必须小于2MB!");
        return false;
      }
      return true;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 从 cookie 中获取 token
    getTokenFromCookie() {
      const cookies = document.cookie.split("; ");
      console.log(cookies);
      console.log();
      const token = cookies
        .find((row) => row.startsWith("token="))
        ?.split("=")[1];
      console.log(token);
      return token;
    },
    // 设置 headers
    setHeaders() {
      this.headers = {
        token: Cookies.get("token"),
      };
    },

    //新增帖子
    mod() {
      if (this.form.parentTypeId && this.form.typeId) {
        modPosts(this.postId, this.form).then((res) => {
          if (res.code == 20000) {
            this.$message.success("修改帖子成功");
            this.$router.push("/userInfoForm");
          } else {
            this.$message.error("修改帖子失败，请稍后再试！");
          }
        });
      } else {
        this.$message.error("请选择帖子类型");
      }
    },
    //获取帖子详细信息
    queryDetails() {
      getIdPost(this.postId).then((res) => {
        console.log(res);
        console.log(this.postId);
        if (res.code == 20000) {
          this.form = res.data.post;
          this.content = res.data.post.content;
          this.postImage = res.data.post.postImage
          console.log(this.form);
        }
      });
    },

    //查询所有的帖子类型
    getAllCommentTypes() {
      getAllCommentType().then((res) => {
        if (res.code == 20000) {
          this.commentTypeList = [];
          res.data.List.forEach((item) => {
            // 检查 commentTypeList 是否存在且有元素
            if (
              Array.isArray(item.commentTypeList) &&
              item.commentTypeList.length > 0
            ) {
              item.commentTypeList.forEach((subItem) => {
                // 确保 subItem 存在
                if (
                  subItem &&
                  subItem.id &&
                  subItem.parentId == this.form.parentTypeId
                ) {
                  this.commentTypeList.push(subItem);
                }
              });
            }
          });
        }

        console.log(this.commentType);
        console.log(this.commentTypeList);
      });
    },
    getParentCommentTypes() {
      getParentCommentType().then((res) => {
        if (res.code == 20000) {
          this.commentType = res.data.parentList;
        }
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  mounted() {
    this.setHeaders();
    this.getParentCommentTypes();
    this.queryDetails();
    if (process.client) {
      const { quillEditor } = require("vue-quill-editor");
      const {
        Select,
        Button,
        Option,
        Upload,
        Switch,
        Message,
      } = require("element-ui");
      this.$options.components = {
        quillEditor,
        [Select.name]: Select,
        [Button.name]: Button,
        [Option.name]: Option,
        [Upload.name]: Upload,
        [Switch.name]: Switch,
        [Message.name]: Message,
      };
      this.editorReady = true;
    }
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
  <style scoped>
  .el-upload__tip {/* 图片上传         */
    font-size: 12px;
    color: #606266;
    margin-top: 7px;
    margin-left: 160px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed black;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  i.el-icon-plus.avatar-uploader-icon {
    border: 1px dashed black;
    margin-left: 160px;
  }
  .avatar {/* 图片的样式         */
    width: 100%;
    height: 250px;
    display: block;
    margin-top: 10px;
    margin-left: 160px;
  }
.header {
  margin-left: 10px;
  margin-top: 10px;
  font-size: 20px;
}
hr {
  height: 1px; /* 设置高度 */
  color: #8f8f8f; /* 设置颜色，也影响阴影 */
  background-color: #adacac; /* 设置背景色 */
  border: none; /* 移除默认边框 */
  margin: 10px 0; /* 设置上下方的外边距 */
  border-radius: 5px; /* 设置圆角 */
  opacity: 0.3; /* 设置透明度 */
}
.select {
  display: flex;
}
.selectTitle {
  margin-top: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}
.header-content {
  margin-left: 150px;
  width: 80%;
  display: flex;
  justify-content: space-between;
}
.header-button {
  display: flex;
  align-items: center;
}
.el-button {
  height: 40px;
  width: 100px;
  margin-top: 10px;
  margin-bottom: 10px;
}

/* 编辑器高度及背景色 */
::v-deep .ql-editor {
  min-height: 300px;
  background-color: #fff;
}
.my-quill-editor {
  height: 300px;
  margin-bottom: 60px;
}

.upload-demo {
  width: 300px;
  margin-left: 160px;
}
</style>
